package com.android.equipment.ui.work

import android.content.Intent
import android.graphics.Color
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Bundle
import android.view.View
import com.android.equipment.AlamViewModel
import com.android.equipment.R
import com.android.equipment.adapter.WorkContactAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.base.BaseApplication
import com.android.equipment.bean.RealDataBean
import com.android.equipment.config.Constant
import com.android.equipment.dao.Work
import com.android.equipment.dao.WorkDetail
import com.android.equipment.dao.operate.DaoDevice
import com.android.equipment.dao.operate.DaoTeamGroup
import com.android.equipment.dao.operate.DaoTeamGroupDetail
import com.android.equipment.dao.operate.DaoWork
import com.android.equipment.dao.operate.DaoWorkDetail
import com.android.equipment.databinding.ActivityWorkDetailBinding
import com.android.equipment.ui.dialog.ContactDialog
import com.android.equipment.ui.dialog.DeviceNodeDetailDialog
import com.android.equipment.ui.dialog.EvidenceDialog
import com.android.equipment.utils.ToastUtil
import com.android.equipment.utils.UiDataHandler
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup


class WorkDetailActivity : BaseActivity<ActivityWorkDetailBinding>() {
    lateinit var work: Work
    private lateinit var workContactAdapter: WorkContactAdapter
    private var workDetailBeanList: MutableList<WorkDetail> = mutableListOf()
    private var isEdit = false
    private var realAlamList: MutableList<RealDataBean> = mutableListOf()

    override fun setLayoutContent(): ActivityWorkDetailBinding {
        return ActivityWorkDetailBinding.inflate(layoutInflater)
    }

    override fun initView(savedInstanceState: Bundle?) {


    }

    override fun initData() {
        val workId = intent.getLongExtra("workId", 0L);
        work = DaoWork.getInstance().getWork(workId)
        binding.mTitleBar.title = work.name
        initRecycler()
        setWorkInfo()
        //setWorkDetailInfo()

    }

    override fun initEvent() {
        //实时数据的监听
        AlamViewModel.getInstance().realData.observe(this) {
            //传过来的数据是 $workId,$deviceCode = RealDataBean
            if (work.status == 1) { //如果当前是正在进行中的作业
                it.forEach { (key, value) ->
                    val split = key.split(",")
                    val workId = split[0]
                    val deviceCode = split[1]
                    if (work.id == workId.toLong()) {
                        val detail =
                            workDetailBeanList.find { detail -> detail.deviceCode == deviceCode }
                        detail?.deviceNodeJson = GsonUtils.toJson(value)
                        detail?.deviceDataChangeTime = TimeUtils.getNowString()
                        workContactAdapter.setList(workDetailBeanList)
                    }
                }
                LogUtils.e("实时数据的监听=======>")
            }
        }


        //实时报警数据监听
        AlamViewModel.getInstance().realAlamData.observe(this) {
            realAlamList.clear()
            //传过来的数据是这样的 ${detail.workId},$deviceCode,${item.node}
            if (work.status == 1) {
                LogUtils.e("实时报警监听=======>$it")
                val split = it.split(",")
                val workId = split[0]
                val deviceCode = split[1]
                //val node = split[2]
                if (work.id == workId.toLong()) {
                    val detail =
                        workDetailBeanList.findIndexed { detail -> detail.deviceCode == deviceCode }
                    workContactAdapter.notifyItemChanged(detail.second)
                }
            }

        }

        //异常报警数据监听
        AlamViewModel.getInstance().errorAlamData.observe(this) {
            realAlamList.clear()
            //传过来的数据是这样的 ${detail.workId},$deviceCode,${item.node}
            if (work.status == 1) {
                val split = it.split(",")
                val workId = split[0]
                val deviceCode = split[1]
                //val node = split[2]
                if (work.id == workId.toLong()) {
                    val detail =
                        workDetailBeanList.findIndexed { detail -> detail.deviceCode == deviceCode }
                    workContactAdapter.getItem(detail.second).isErrorAlam = true
                    workContactAdapter.notifyItemChanged(detail.second)
                }
            }

        }

        binding.tvRelevanceDevice.setOnClickListener {
            XPopup.Builder(mContext)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asCustom(
                    ContactDialog(
                        this@WorkDetailActivity,
                        workDetailBeanList,
                        work.id,
                        object : ContactDialog.OnConfirmListener {
                            override fun onConfirm(newWorkDetailList: MutableList<WorkDetail>) {
                                workDetailBeanList.addAll(newWorkDetailList)
                                workContactAdapter.setList(workDetailBeanList)
                                if (work.status == 1) {
                                    DaoWorkDetail.getInstance().addWorkDetail(workDetailBeanList)
                                    work.peopleNum = workContactAdapter.data.size
                                    DaoWork.getInstance().updateWork(work)
                                }
                            }

                        })
                ).show()
        }




        binding.llRelevanceDevice.setOnClickListener {
            XPopup.Builder(mContext)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asCustom(
                    ContactDialog(
                        this@WorkDetailActivity,
                        workDetailBeanList,
                        work.id,
                        object : ContactDialog.OnConfirmListener {
                            override fun onConfirm(newWorkDetailList: MutableList<WorkDetail>) {
                                workDetailBeanList.addAll(newWorkDetailList)
                                workContactAdapter.setList(workDetailBeanList)
                                if (work.status == 1) {
                                    DaoWorkDetail.getInstance().addWorkDetail(workDetailBeanList)
                                    work.peopleNum = workContactAdapter.data.size
                                    DaoWork.getInstance().updateWork(work)
                                }
                            }

                        })
                ).show()
        }

        binding.tvAppendTeam.setOnClickListener {
            val allTeamGroup = DaoTeamGroup.getInstance().allTeamGroup

            if (allTeamGroup.isEmpty()) {
                ToastUtil.showToastSafe("请先创建班组")
                return@setOnClickListener
            }
            XPopup.Builder(mContext)
                .asBottomList(
                    "选择班组", allTeamGroup.map { it.groupName }.toTypedArray()
                ) { position, value ->

                    val groupId = allTeamGroup[position].id
                    val teamGroupDetails =
                        DaoTeamGroupDetail.getInstance().getTeamGroupDetailByGroupId(groupId)
                    teamGroupDetails.forEach {
                        val device = DaoDevice.getInstance().getDevice(it.deviceId)
                        val workDetail = WorkDetail()
                        workDetail.workId = work.id
                        workDetail.workName = work.name
                        workDetail.peopleId = it.peopleId
                        workDetail.peopleName = it.peopleName
                        workDetail.peoplePhone = it.peoplePhone
                        workDetail.peoplePhoto = it.peoplePhoto

                        workDetail.deviceId = it.deviceId
                        workDetail.deviceName = it.deviceName
                        workDetail.deviceCode = it.deviceCode
                        workDetail.deviceModelId = device.deviceModelId
                        val defaultNodeData =
                            UiDataHandler.handlerDefaultNodeData(device.deviceModelId)
                        workDetail.deviceNodeJson = GsonUtils.toJson(defaultNodeData)

                        //val workDetailBean = WorkDetailBean(it.deviceId,deviceCode, deviceChangeTime, alarmData, it.peopleId,peopleName, peoplePhone)
                        workDetailBeanList.add(workDetail)
                    }
                    workContactAdapter.setList(workDetailBeanList)

                }
                .show()
        }

        binding.mTitleBar.leftView.setOnClickListener {
            mSwipeBackHelper.backward()
        }

        binding.mTitleBar.rightView.setOnClickListener {
            when (work.status) {
                1 -> {  //进行中  编辑
                    isEdit = !isEdit
                    if (isEdit) {
                        binding.mTitleBar.rightView.text = "完成"
                        binding.mTitleBar.rightView.setTextColor(Color.parseColor("#1D2129"))
                        binding.llRelevanceDevice.visibility = View.VISIBLE
                        binding.llObtainEvidence.visibility = View.GONE
                        workContactAdapter.setEditState(true)
                    } else {
                        binding.mTitleBar.rightView.text = "编辑"
                        binding.mTitleBar.rightView.setTextColor(Color.parseColor("#42E7AF"))
                        binding.llRelevanceDevice.visibility = View.GONE
                        binding.llObtainEvidence.visibility = View.VISIBLE
                        workContactAdapter.setEditState(false)

                    }
                }

                2 -> {  //已完成 跳转到历史报警
                    val intent = Intent(this, HistoryAlamActivity::class.java)
                    intent.putExtra("workId", work.id)
                    mSwipeBackHelper.forward(intent)
                }
            }
        }

        binding.tvStartWork.setOnClickListener {

            if (workDetailBeanList.isEmpty()) {
                ToastUtil.showToastSafe("请先关联设备")
                return@setOnClickListener
            }

            XPopup.Builder(mContext)
                .asConfirm(
                    "提示", "确定要开始作业吗?"
                ) {
                    startWork()
                }.show()


        }

        binding.tvEndWork.setOnClickListener {
            XPopup.Builder(mContext)
                .asConfirm(
                    "提示", "确定要结束当前作业吗?"
                ) {
                    endWork()
                }.show()


        }

        binding.llObtainEvidence.setOnClickListener {
            XPopup.Builder(mContext)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asCustom(
                    EvidenceDialog(
                        this@WorkDetailActivity,
                        work.id
                    ).show()
                )
        }

    }

    private fun initRecycler() {
        workContactAdapter =
            WorkContactAdapter(R.layout.item_work_contact_info, work.id, work.status)
        binding.rvContact.adapter = workContactAdapter
        workContactAdapter.addChildClickViewIds(R.id.ll_device_node_info)
        workContactAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ll_device_node_info) {
                val workDetail = workContactAdapter.data[position]
                val type = GsonUtils.getListType(RealDataBean::class.java)
                val realDataList: MutableList<RealDataBean> =
                    GsonUtils.fromJson(workDetail.deviceNodeJson, type)
                XPopup.Builder(mContext)
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asCustom(
                        DeviceNodeDetailDialog(
                            this,
                            work.id,
                            workDetail.deviceCode,
                            workDetail.isHaveAlam,
                            realDataList
                        )
                    )
                    .show()
            }
        }


//        { adapter, view, position ->
//            XPopup.Builder(mContext)
//                .asConfirm("确定要删除吗？", "") {
//                    workContactAdapter.removeAt(position)
//                    if (work.status == 1) {
//                        DaoWorkDetail.getInstance().delWorkDetail(workDetailBeanList[position])
//                        work.peopleNum = workContactAdapter.data.size
//                        DaoWork.getInstance().updateWork(work)
//                    }
//                }.show()
//            true
//        }
    }

    fun <T> List<T>.findIndexed(predicate: (T) -> Boolean): Pair<T?, Int> {
        for ((index, element) in this.withIndex()) {
            if (predicate(element)) {
                return Pair(element, index)
            }
        }
        return Pair(null, -1)  // 如果没有找到，返回 null 和 -1
    }


    private fun startWork() {
        DaoWorkDetail.getInstance().addWorkDetail(workDetailBeanList)
        work.status = 1
        work.beginTime = TimeUtils.getNowString()
        work.peopleNum = workDetailBeanList.size
        DaoWork.getInstance().updateWork(work)
        setWorkInfo()
    }

    private fun endWork() {
        work.status = 2
        work.endTime = TimeUtils.getNowString()
        work.peopleNum = workDetailBeanList.size
        DaoWork.getInstance().updateWork(work)
        setWorkInfo()
    }

    private fun setWorkInfo() {
        work = DaoWork.getInstance().getWork(work.id)
        workContactAdapter.updateAdapterWorkState(work.status)

        binding.tvWorkName.text = work.name
        binding.tvCreateTime.text = work.addTime
        binding.tvStatus.text = Constant.workList[work.status]

        binding.ivBg.visibility = if (work.status == 0) View.VISIBLE else View.GONE
        binding.llWorkInfo.visibility = if (work.status == 0) View.VISIBLE else View.GONE
        binding.tvStartWork.visibility = if (work.status == 0) View.VISIBLE else View.GONE
        binding.tvEndWork.visibility = if (work.status == 1) View.VISIBLE else View.GONE
        binding.llObtainEvidence.visibility = if (work.status != 0) View.VISIBLE else View.GONE
        binding.llRelevanceDevice.visibility = View.GONE

        when (work.status) {
            0 -> { //待开始
                binding.tvStatus.setTextColor(Color.parseColor("#FF7800"))
            }

            1 -> {  //进行中
                binding.tvStatus.setTextColor(Color.parseColor("#00A652"))
                binding.mTitleBar.rightView.apply {
                    text = "编辑"
                    textSize = 14f
                    setTextColor(Color.parseColor("#42E7AF"))
                }
                val workDetailList = DaoWorkDetail.getInstance().getWorkDetailByWorkId(work.id)
                workDetailList.forEach {
                    val deviceCode = it.deviceCode
                    val deviceModelId = it.deviceModelId
                    val lastTimeNodeData =
                        UiDataHandler.getLastTimeNodeData(
                            deviceCode,
                            deviceModelId,
                            TimeUtils.string2Millis(work.beginTime),
                            null
                        )
                    if (lastTimeNodeData.isNotEmpty()) {
                        it.deviceNodeJson = GsonUtils.toJson(lastTimeNodeData)
                    }

                }

                workDetailList?.let {
                    workDetailBeanList.clear()
                    workDetailBeanList.addAll(it)
                    workContactAdapter.setList(it)
                    workContactAdapter.setEditState(false)
                }
            }

            2 -> {  //已完成
                binding.tvStatus.setTextColor(Color.parseColor("#636363"))
                binding.mTitleBar.rightView.apply {
                    text = "历史报警"
                    textSize = 14f
                    setTextColor(Color.parseColor("#1D2129"))
                }
                val workDetailList = DaoWorkDetail.getInstance().getWorkDetailByWorkId(work.id)
                workDetailList.forEach {
                    val deviceCode = it.deviceCode
                    val deviceModelId = it.deviceModelId
                    val lastTimeNodeData =
                        UiDataHandler.getLastTimeNodeData(
                            deviceCode,
                            deviceModelId,
                            TimeUtils.string2Millis(work.beginTime),
                            TimeUtils.string2Millis(work.endTime)
                        )
                    if (lastTimeNodeData.isNotEmpty()) {
                        it.deviceNodeJson = GsonUtils.toJson(lastTimeNodeData)
                    }

                }
                workDetailList?.let {
                    workDetailBeanList.clear()
                    workDetailBeanList.addAll(it)
                    workContactAdapter.setList(it)
                    workContactAdapter.setEditState(false)
                }
            }
        }
    }


    override fun setStatusBar() {
        ImmersionBar.with(this)

            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .fullScreen(false)
            .init()
    }
}